<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="formRef" :model="formData" label-width="100px">
        <el-form-item label="产品名称" prop="product">
          <el-input v-model="formData.product" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="每份数量" prop="quantity">
          <el-input v-model="formData.quantity" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="总数量" prop="quantity">
          <el-input v-model="formData.quantity" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handlePrint">打印标签</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never">
      <vxe-grid :data="records" :columns="columns" border />
    </el-card>
  </div>
</template>

<script lang="ts" setup>
defineOptions({
  name: "Printer",
  inherititems: false,
});
import ZebraBrowserPrintWrapper from "zebra-browser-print-wrapper-v2";
import axios from "axios";

interface printer {
  serial: string;
  customer: string;
  dwg: string;
  product: string;
  product_name: string;
  quantity: number;
  date: string;
  create_user: string;
}
interface MessageRecord {
  barcode: string;
  product: string;
  quantity: number;
  timestamp: string;
  message: string;
}

const formRef = ref(null);

const formData = reactive({
  product: "",
  quantity: "",
});
const records = ref<MessageRecord[]>([]);

const columns = ref<(typeof VxeGridProps)["columns"]>([
  { field: "barcode", title: "条码", width: 300 },
  { field: "product", title: "产品", width: 200 },
  { field: "quantity", title: "数量", width: 100 },
  { field: "timestamp", title: "操作时间", width: 200 },
  { field: "message", title: "信息" },
]);

const handlePrint = () => {
  const printData: printer = {
    serial: "123456",
    customer: "Customer Name",
    dwg: "DWG123",
    product: formData.product,
    product_name: formData.product,
    quantity: Number(formData.quantity),
    date: new Date().toISOString(),
    create_user: "User123",
  };
  printBarcode(printData);
};

// Create a singleton instance of ZebraBrowserPrintWrapper
const browserPrint = new ZebraBrowserPrintWrapper();
let defaultPrinter: any = null;

const printBarcode = async (obj: printer) => {
  try {
    // Cache the default printer instance
    if (!defaultPrinter) {
      defaultPrinter = await browserPrint.getDefaultPrinter();
      browserPrint.setPrinter(defaultPrinter);
    }

    // Check printer status
    const printerStatus = await browserPrint.checkPrinterStatus();

    if (!printerStatus.isReadyToPrint) {
      ElMessage.error(`Printer not ready: ${printerStatus.errors}`);
    }

    // Optimize ZPL by removing unnecessary whitespace
    const zpl = `^XA^BY2,2,100^FO20,20^BC^FD${obj.serial}^FS^XZ`;

    // Use Promise.all to fetch template and process it concurrently
    const [response] = await Promise.all([axios.get("/path/to/your/template.lbl")]);

    // Template processing
    const lblTemplate = response.data
      .replace("{productName}", obj.product_name)
      .replace("{quantity}", obj.quantity)
      .replace("{date}", obj.date)
      .replace("{create_user}", obj.create_user)
      .replace("{serial}", obj.serial)
      .replace("{dwg}", obj.dwg)
      .replace("{product}", obj.product)
      .replace("{customer}", obj.customer);

    await browserPrint.print(zpl);
    records.value.push({
      barcode: obj.serial,
      product: obj.product,
      quantity: obj.quantity,
      timestamp: new Date().toISOString(),
      message: "打印成功",
    });
  } catch (error) {
    // Specific error handling
    if (error instanceof Error) {
      records.value.push({
        barcode: obj.serial,
        product: obj.product,
        quantity: obj.quantity,
        timestamp: new Date().toISOString(),
        message: `标签打印失败: ${error.message}`,
      });
    } else {
      records.value.push({
        barcode: obj.serial,
        product: obj.product,
        quantity: obj.quantity,
        timestamp: new Date().toISOString(),
        message: `标签打印失败: 未知错误`,
      });
    }
  }
};

// Add cleanup method
const cleanupPrinter = () => {
  defaultPrinter = null;
};
</script>

<style scoped>
.printer-container {
  padding: 20px;
}
</style>
